var ds,grid;
var fp,win;
var module_win,module_tree;

var buildGrid = function(){
    ds = new Ext.data.JsonStore({
        url:'role!list.action',
        root:'items',
        totalProperty:'total',
        idProperty:'role.id',
        fields:['role.id','role.code','role.name']
    });
    grid = new Ext.grid.EditorGridPanel({
        store:ds,
        columns:[
            new Ext.grid.RowNumberer(),
            {header:'角色名',width:150,sortable:true,dataIndex:'role.name'},
            {header:'角色编码',width:150,sortable:true,dataIndex:'role.code'}
        ],
        renderTo:'grid',
        border:true,
        clicksToEdit:2,
        selModel:new Ext.grid.RowSelectionModel(),
        tbar:[{
				text:'新增',
				iconCls:'admin-tool-add',
				handler:newRole
			  },'-',{
				text:'编辑',
				iconCls:'admin-tool-edit',
				handler:editRole
			  },'-',{
                text:'删除',
                iconCls:'admin-tool-delete',
                handler:destroyRole
              },'-',{
				text:'角色权限',
				iconCls:'admin-tool-role',
				handler:editRoleModule
              }],
        
        bbar : new Ext.PagingToolbar({
			store : ds,
			displayInfo : true
		})
    });
    
    ds.load({params:{start:0,limit:30}});
};

var buildWin = function(){
    fp = new Ext.form.FormPanel({
        labelWidth:60,
        labelAlign:'right',
        bodyStyle:'padding:10px',
        items:[{
            layout:'column',
            border:false,
            defaults:{border:false},
            items:[{
                columnWidth:.5,
                layout:'form',
                defaultType:'textfield',
                defaults:{width:180},
                items:[{
                    fieldLabel:'角色名称',
                    name:'role.name',
                    allowBlank:false
                },{
                    fieldLabel:'角色编码',
                    name:'role.code',
                    allowBlank:false
                }]
            }]
        }]
    });
    
    win = new Ext.Window({
        el:'win',
        width:600,
        height:385,
        closeAction:'hide',
        layout:'fit',
        modal:true,
        items:fp,
        buttons:[{
            text:'保存',
            handler:saveRole
        },{
            text:'取消',
            handler:function(){win.hide();}
        }]
    });
    
};
var buildLayout = function(){
    new Ext.Viewport({
        layout:'border',
        defaults:{border:false},
        items:[{
            region:'north',
            contentEl:'north-div',
            title:'角色设置'
        },{
            region:'center',
            layout:'fit',
            items:grid
        }]
    });
};

var init = function(){
    buildGrid();
    buildWin();
  	buildLayout();
};

Ext.onReady(init);


var newRole = function(){
	win.setTitle('新建角色资料');
	win.show();
	fp.form.reset();
	fp.url = 'role!save.action';
};

var editRole = function(){
	var rec = grid.getSelectionModel().getSelected();
    if (rec){
        win.setTitle('修改角色资料');
        win.show();
        fp.form.reset();
        fp.form.loadRecord(rec);
        fp.url = 'role!save.action?role.id='+rec.id;
    }
};

var saveRole = function(){
	if (fp.form.isValid() == false){
        return;
    }
    fp.form.submit({
        url:fp.url,
        success:function(){
            win.hide();
            ds.reload();
            Ext.MessageBox.alert('提示','提交成功!');
        },
        failure:function(form,action){
            Ext.MessageBox.alert('警告','提交失败!');
        }
    })
};

var destroyRole = function(){

	var rows = grid.getSelectionModel().getSelections();
	
	if (rows.length == 0){
		Ext.Msg.alert("提示", "您还没有选择任何角色！");
		return;
	}
	var ids = [];
	if (rows.length > 0){
		for (var i = 0; i < rows.length; i++) {
			ids.push(rows[i].data['role.id']);
		}
	}
	Ext.MessageBox.confirm("删除确认", "是否真的删除选定的资料?", function(btn){
		if(btn=='yes'){
			Ext.Ajax.request({
				url:'role!delete.action',
				method:'POST',
				params:{'ids':ids},
				success:function(response){
					var data = Ext.util.JSON.decode(response.responseText);
					if (data.success){            
				        ds.reload();
				        Ext.MessageBox.alert('提示','删除角色资料完成。');
			        }
					else{
			            Ext.MessageBox.alert('警告','删除角色资料失败。');
					}
				}
			})
		}
	});
};


var buildRoleModuleWin = function(){
	
	var rec = grid.getSelectionModel().getSelected();
	
	var root = new Ext.tree.AsyncTreeNode({
        id:'0',
        text:'模块功能树'
    });
    
    module_tree = new Ext.tree.TreePanel({
        loader:new Ext.tree.TreeLoader({
        	dataUrl:'role!getModuleTrees.action?parent_id=0&role_id='+rec.id,
        	baseAttrs : {
				uiProvider:Ext.ux.TreeCheckNodeUI
			}
		}),
		id:'treePanel',
        root:root,
        renderTo:'tree',
        border:false,
        autoScroll:true,
        checkModel: 'cascade'
    });
   
    module_tree.getRootNode().expand(true);
    
    module_tree.on('click',function(node){
        node.expand();
        node.select();
    });
    
    module_tree.on('beforeload',function(node) {
        module_tree.loader.dataUrl = 'role!getModuleTrees.action?parent_id='+node.id+'&role_id='+rec.id;
    });
	
	module_win = new Ext.Window({
        //el:'module-win',
        width:600,
        height:385,
        closeAction:'hide',
        layout:'fit',
        modal:true,
        items:module_tree,
        buttons:[{
            text:'保存',
            handler:saveRoleModule
        },{
            text:'取消',
            handler:function(){module_win.hide();}
        }]
    });
};

var editRoleModule = function(){
	
	buildRoleModuleWin();
	
	module_win.setTitle('配置角色权限');
	module_win.show();
};

var saveRoleModule = function(){
	
	var rec = grid.getSelectionModel().getSelected();
	
	var selNodes = Ext.getCmp('treePanel').getChecked();
	var ids = [];
	var params = {};
    Ext.each(selNodes, function(node){
    	ids.push(node.id);
   	});
   	
   	params['ids'] = ids;
	
	Ext.Ajax.request({
		url : 'role!saveRoleModule.action?role.id='+rec.id,
		params : params,
		method : 'POST',
		success : function(response) {
			module_win.hide();
			Ext.MessageBox.alert('提示','角色权限保存成功!');
		}
	})
};